/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package exatrez.manager;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.wideplay.warp.persist.Transactional;
import exatrez.dao.EmailDAO;
import exatrez.model.*;
import exatrez.stripes.util.EmailUtil;
import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import java.io.File;
import java.io.StringWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author fikri
 */
public class EmailManager {

    @Inject
    private EmailDAO dao;
    @Inject
    protected com.google.inject.Provider<Session> sessionProvider;
    @Inject
    Provider<SessionFactory> sp;
    @Inject
    exatrez.stripes.Configuration conf;
    @Inject
    private EmailUtil emailUtil;
    private static Logger LOG = LoggerFactory.getLogger(EmailManager.class);
    private String fromUser;
    private String toUser;
    private String emailAddr;
    private String vessel;
    private String dateInspection;
    private String severity;
    private String crewEmail;
    private String procEmail;

    @Transactional
    public void save(Email email) {
        dao.saveOrUpdate(email);
    }

    public List<Email> getEmailList() {
        String query = "SELECT a FROM Email a WHERE a.active = :active  ";
        Query q = sessionProvider.get().createQuery(query);
        q.setParameter("active", "Y");
        return q.list();
    }

    public Email findById(Integer id) {
        return dao.findById(id);
    }

    public String findEmailByPengguna(String idPengguna) {

        String eml = "";

        StringBuilder sb = new StringBuilder("select p from User p ").append("where userId = :id ");
        Session session = sessionProvider.get();
        Query query = session.createQuery(sb.toString()).setParameter("id", idPengguna);

        User user = (User) query.uniqueResult();
        if (user != null) {
            eml = user.getEmail();
        }

        return eml;
    }

    public void ackEmailProcess() {
//        if (!getHistoryList().isEmpty()) {
//            List<Map<String, String>> tasks = getTasks();
//            if (StringUtils.isNotBlank(toUser) && StringUtils.isNotBlank(fromUser)
//                    && StringUtils.isNotBlank(emailAddr) && !tasks.isEmpty()){
//                sendEmail(tasks);
//            }
//        }        

        List<Inbox> inboxs = getInbox();
        if (inboxs != null && !inboxs.isEmpty()) {
            for (Inbox inbox : inboxs) {
                String[] combine = {inbox.getReceiverEmail()};
//                String [] coo = {getCooEmail()};
                String[] recipient = (String[]) ArrayUtils.addAll(combine, conf.getProperty("email.obs.to").split(","));

                String[] coo = (String[]) ArrayUtils.addAll(conf.getProperty("email.coo").split(","),
                        getMaEmail());
                emailUtil.send(recipient, coo, inbox.getTitle(), inbox.getContent(), "text/html");
            }
            updateInbox(inboxs);
        }
    }

    public void beforeAfterDueDate() {
        String ftlFile = "html-reminder.ftl";
        beforeDueDate("1", ftlFile, "LOW");
        beforeDueDate("2", ftlFile, "MEDIUM");
        beforeDueDate("3", ftlFile, "HIGH");
//        if (!list.isEmpty()) {
//            severity = "LOW";
//            sendEmail(list, ftlFile, "WARNING : OBSERVATION REMINDER");
//        }
//        list = beforeDueDate("2");
//        if (!list.isEmpty()) {
//            severity = "MEDIUM";
//            sendEmail(list, ftlFile, "WARNING : OBSERVATION REMINDER");
//        }
//        list = beforeDueDate("3");
//        if (!list.isEmpty()) {
//            severity = "HIGH";
//            sendEmail(list, ftlFile, "WARNING : OBSERVATION REMINDER");
//        }
    }

    public void closeObservation() {

        String ftlFile = "html-close.ftl";
        List<Map<String, String>> list = closeObservationTask();
//        StatelessSession ss = null;
        try {
//            ss = sp.get().openStatelessSession();
//            Query query2 = ss.createQuery("from Vessel u where u.vesselName = :vessel").setParameter("vessel", vessel);
//                        Vessel v = (Vessel) query2.uniqueResult();
//                        String crewEmail = v.getCrewExe().getEmail();
//                        String procEmail = v.getProcExe().getEmail();
            if (!list.isEmpty()) {
                sendEmail(list, ftlFile, "ALERT : OBSERVATION CLOSED.");
            }
        } catch (Exception ex) {
            LOG.error("error occured {}!! ", ex);
        }
    }

    private void sendEmail(List<Map<String, String>> tasks, String ftlFile, String subject) {

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

        if (StringUtils.isNotBlank(emailAddr)) {
            String[] combine = {emailAddr, crewEmail, procEmail};
            String[] recipient = (String[]) ArrayUtils.addAll(combine, conf.getProperty("email.obs.to").split(","));

            String[] ccRecipient = (String[]) ArrayUtils.addAll(conf.getProperty("email.coo").split(","),
                    getMaEmail());
            try {
                // freemarker stuff.
                Configuration cfg = new Configuration();
                FileTemplateLoader templateLoader = new FileTemplateLoader(new File(conf.getProperty("email.template.path")));
                cfg.setTemplateLoader(templateLoader);
                cfg.setObjectWrapper(new DefaultObjectWrapper());
                Template template = cfg.getTemplate(ftlFile);
                Map<String, Object> rootMap = new HashMap<String, Object>();
                rootMap.put("severity", severity);
                rootMap.put("vessel", vessel);
                if (tasks != null) {
                    rootMap.put("tasks", tasks.toArray());
                }
                rootMap.put("dateInspection", dateInspection);
                rootMap.put("dateToday", sdf.format(new Date()));
                if (StringUtils.isNotBlank(toUser)) {
                    rootMap.put("to", toUser);
                }
                if (StringUtils.isNotBlank(fromUser)) {
                    rootMap.put("from", fromUser);
                }

                Writer out = new StringWriter();
                template.process(rootMap, out);
                emailUtil.send(recipient, ccRecipient, subject, out.toString(), "text/html");
                // freemarker stuff ends.
            } catch (Exception ex) {
                LOG.error("error occured {}!! ", ex);
            }
        }
    }

    private List<Inbox> getInbox() {
        StatelessSession ss = null;
        try {
            ss = sp.get().openStatelessSession();
            Query query = ss.createQuery("Select p from Inbox p where p.status.inboxStsCodeId = :id").setInteger("id", 1);
            return query.list();


        } catch (Exception ex) {
        }
        return Collections.EMPTY_LIST;
    }

    private void updateInbox(List<Inbox> inboxs) {
        Session ss = null;
        Transaction tx = null;
        try {
            ss = sp.get().openSession();
            tx = ss.beginTransaction();
            InboxStatusCode status = (InboxStatusCode) ss.createQuery("Select p from InboxStatusCode p where inboxStsCodeId = 3").uniqueResult();


            for (Inbox inbox : inboxs) {
                Criteria query = ss.createCriteria(Inbox.class).add(Restrictions.eq("inboxId", inbox.getInboxId()));
                Inbox in = (Inbox) query.uniqueResult();
                in.setStatus(status);
                InfoAudit ia = in.getInfoAudit();
                if (ia != null) {
                    ia.setUpdateDate(new Date());
                    in.setInfoAudit(ia);
                }
                ss.update(in);
            }
            tx.commit();
        } catch (HibernateException ex) {
            tx.rollback();
            LOG.error(null, ex);
        } finally {
            if (ss != null) {
                ss.close();
            }
        }
    }

//     public String[] getMaEmail() {
//        
//        StringBuilder sb = new StringBuilder("select p from UserGroup p ")
//                .append("where p.group.groupId = :group");
//        Session session = sessionProvider.get();
//        Query query = session.createQuery(sb.toString()).setInteger("group", 1);
//        if (!query.list().isEmpty()) {
//            String[] emails = new String[query.list().size()];
//            List<UserGroup> userGroups = query.list();
//            for (int i=0; i<userGroups.size();i++) {
//                UserGroup ug = userGroups.get(i);
//                if (ug.getUser() != null) {
//                    emails[i] = ug.getUser().getEmail();
//                }
//            }
//            return emails;
//        }
//        return null;
//    }
//    edited by mansur since sessionProvider is not suitable for cronjobs session
    public String[] getMaEmail() {

        StatelessSession ss = null;
        try {
            ss = sp.get().openStatelessSession();
            LOG.debug("getMaEmail session start");
            Query query = ss.createQuery("select u from UserGroup p, User u where p.user.userId = u.userId and p.user.userId != 'abu.audit' and p.group.groupId = :group").setInteger("group", 1);
            LOG.debug("getMaEmail.query.list :" + query.list().size());
            if (query.list().size() != 0) {
                String[] emails = new String[query.list().size()];
                List<User> user = query.list();
                LOG.debug("userGroups.size :" + user.size());
                LOG.debug("emails.length :" + emails.length);
                int i = 0;
                for (User u : user) {
                    LOG.debug("count i = " + i + "userid :" + u.getUserId());
                    emails[i] = u.getEmail();
                    LOG.debug("emails[" + i + "] = " + emails[i]);
                    i++;
                }
                LOG.debug("getMaEmail.length :" + emails.length);
                return emails;
            }
        } catch (Exception ex) {
            return null;
        }
        return null;
    }

    public List<ObservationHistoryTask> getHistoryList() {
        StatelessSession ss = null;

        try {
            Calendar cal = Calendar.getInstance();
//            cal.add(Calendar.DATE, -1);

            ss = sp.get().openStatelessSession();

            return ss.createQuery("Select p from ObservationHistoryTask p where date(p.responseDate) = :date").setParameter("date", cal.getTime()).list();

        } catch (HibernateException ex) {
            LOG.error(null, ex);
        } finally {
            if (ss != null) {
                ss.close();
            }
        }

        return Collections.EMPTY_LIST;
    }

    private void beforeDueDate(String code, String ftlFile, String severity) {

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

        StatelessSession ss = null;
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 3);

        Calendar cal3 = Calendar.getInstance();

        try {
            ss = sp.get().openStatelessSession();
            Query query = ss.createQuery("Select p.observationId, date(p.dateOfInspection), p.vessel.vesselName, "
                    + "p.assignee.email, date(p.dateSubmit), p.vessel.vesselId "
                    + "from Observation p where p.status.statusRemarkCodeId = :id ");
            query.setParameter("id", 2);
            List<Object[]> listOfObj = query.list();
            for (Object[] obj : listOfObj) {
                if (obj != null) {
                    List<Map<String, String>> list = new ArrayList<Map<String, String>>();
                    String observationId = obj[0].toString();
                    dateInspection = sdf.format((Date) obj[1]);
                    vessel = obj[2].toString();
                    emailAddr = obj[3].toString();
                    String vesselId = obj[5].toString();
                    this.getCrewProcEmail(vesselId);
//                    List<ObservationTask> tasks = obs.getTaskList();
//                    Query query2 = ss.createQuery("select u from Vessel v where u.vesselName = :vessel").setParameter("vessel", vessel);
//                    LOG.debug("beforeDueDate : kod = "+code+", query2.size :"+query2.list().size());
//                    LOG.debug("beforeDueDate : kod = "+code+", query2 :"+query2.uniqueResult());
//                    Vessel v = (Vessel) query2.uniqueResult();
//                    String crewEmail = v.getCrewExe() != null ? v.getCrewExe().getEmail() : null;
//                    String procEmail = v.getProcExe() != null ? v.getProcExe().getEmail() : null;
//                    LOG.debug("crewEmail :"+crewEmail);
//                    LOG.debug("procEmail :"+procEmail);

                    List<Object[]> listOfObj2 = ss.createQuery("select p.severity.severityCodeId,p.severityDayCount,"
                            + "p.severityDayAdd, p.observationTaskId, p.title, p.summary "
                            + "from ObservationTask p "
                            + "where p.observation.observationId = :id "
                            + "and p.statusRemarks.statusRemarkCodeId in ('2','3')").setParameter("id", Integer.parseInt(observationId)).list();

                    for (Object[] obj2 : listOfObj2) {
                        if (obj2[0].toString().equals(code)) {
                            Map<String, String> map = new HashMap<String, String>();
                            int days = Integer.parseInt(obj2[1] != null ? obj2[1].toString() : "0");
                            int add = Integer.parseInt(obj2[2] != null ? obj2[2].toString() : "0");
                            Calendar cal2 = Calendar.getInstance();
                            cal2.setTime((Date) obj[4]);
                            cal2.add(Calendar.DATE, days);
                            cal2.add(Calendar.DATE, add);
                            if (cal.compareTo(cal2) == 0) {
                                map.put("obsId", obj2[3] != null ? obj2[3].toString() : "");
                                map.put("title", obj2[4] != null ? obj2[4].toString() : "");
                                map.put("closingAction", obj2[5] != null ? obj2[5].toString() : "");
                                list.add(map);
                            } else if (cal2.compareTo(cal3) < 0) {
                                map.put("obsId", obj2[3] != null ? obj2[3].toString() : "");
                                map.put("title", obj2[4] != null ? obj2[4].toString() : "");
                                map.put("closingAction", obj2[5] != null ? obj2[5].toString() : "");
                                list.add(map);
                            }
                        }
                    }
                    if (!list.isEmpty()) {
                        this.severity = severity;
                        sendEmail(list, ftlFile, "WARNING : OBSERVATION REMINDER");
                    }
                }
            }

        } catch (HibernateException ex) {
            LOG.error(null, ex);
        } finally {
            if (ss != null) {
                ss.close();
            }
        }

//        return list;
    }

    private List<Map<String, String>> closeObservationTask() {

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();

        StatelessSession ss = null;
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);


        try {
            ss = sp.get().openStatelessSession();
            Query query = ss.createQuery("Select p.observationId, date(p.dateOfInspection), p.vessel.vesselName, "
                    + "p.assignee.email, p.assignee.userId, p.infoAudit.createId.userId, p.vessel.vesselId "
                    + "from Observation p where p.status.statusRemarkCodeId = :id "
                    + "and date(p.infoAudit.updateDate) = :date");
            query.setParameter("id", 1); //close
            query.setParameter("date", cal.getTime());
            List<Object[]> listOfObj = query.list();
            for (Object[] obj : listOfObj) {
                if (obj != null) {
                    String observationId = obj[0].toString();
                    dateInspection = sdf.format((Date) obj[1]);
                    vessel = obj[2].toString();
                    emailAddr = obj[3].toString();
                    toUser = obj[4].toString();
                    fromUser = obj[5].toString();
                    String vesselId = obj[6].toString();
                    this.getCrewProcEmail(vesselId);

//                    List<ObservationTask> tasks = obs.getTaskList();

                    List<Object[]> listOfObj2 = ss.createQuery("select "
                            + "p.observationTaskId, p.title, p.summary "
                            + "from ObservationTask p "
                            + "where p.observation.observationId = :id").setParameter("id", Integer.parseInt(observationId)).list();

                    for (Object[] obj2 : listOfObj2) {
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("obsId", obj2[0] != null ? obj2[0].toString() : "");
                        map.put("title", obj2[1] != null ? obj2[1].toString() : "");
                        map.put("closingAction", obj2[2] != null ? obj2[2].toString() : "");
                        list.add(map);
                    }
                }
            }

        } catch (HibernateException ex) {
            LOG.error(null, ex);
        } finally {
            if (ss != null) {
                ss.close();
            }
        }

        return list;
    }

    private List<Map<String, String>> getTasks() {

        StatelessSession ss = null;

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 3);
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

        List<Map<String, String>> list = new ArrayList<Map<String, String>>();

        try {
            ss = sp.get().openStatelessSession();
            Query query = ss.createQuery("Select "
                    + "p.observationTask.observation.observationId "
                    + "from ObservationHistoryTask p where date(p.responseDate) = :date "
                    + "group by p.observationTask.observation.observationId");
            query.setParameter("date", cal.getTime());
            LOG.debug("size {}", query.list().size());
            List<Object[]> listOfObj = query.list();

            for (Object[] obj : listOfObj) {
                LOG.debug("obj {}", obj[0].toString());
                LOG.debug("obj {}", obj[1].toString());


                Map<String, String> map = new HashMap<String, String>();

                String responseUptodate = obj[0].toString();
                String observationId = obj[1].toString();
                if (StringUtils.isNotBlank(observationId)) {
                    query = ss.createQuery("select p from ObservationTask p "
                            + "where p.observation.observationId = :id");
                    query.setParameter("id", Integer.parseInt(observationId));
                    List<ObservationTask> tasks = query.list();
                    if (!tasks.isEmpty()) {
                        int totalObs = tasks.size();
                        ObservationTask task = tasks.get(0);
//                       Observation obs = task.getObservation();
                        List<Object[]> listOfObj2 = ss.createQuery("select p.infoAudit.createId.userId, "
                                + "p.assignee.userId, p.infoAudit.createId.email, p.vessel.vesselName, date(p.dateOfInspection) "
                                + "from Observation p "
                                + "where p.observationId = :id").setParameter("id", Integer.parseInt(observationId)).list();
                        Object[] ob = listOfObj2.get(0);
                        toUser = ob[0].toString();
                        fromUser = ob[1].toString();
                        emailAddr = ob[2].toString();
                        String vessel = ob[3].toString();
                        Date dateInspection = (Date) ob[4];
                        map.put("vessel", vessel);
                        map.put("dateInspection", sdf.format(dateInspection));
                        map.put("totalObs", String.valueOf(totalObs));
                        map.put("responseToDate", responseUptodate);
                        list.add(map);
                    }
                }
            }

        } catch (HibernateException ex) {
            LOG.error(null, ex);
        } finally {
            if (ss != null) {
                ss.close();
            }
        }
        return list;
    }

    private void getCrewProcEmail(String vesseId) {
        StatelessSession ss = null;
        crewEmail = new String();
        procEmail = new String();
        try {
            ss = sp.get().openStatelessSession();
            Query query2 = ss.createQuery("select u from User u, Vessel v where u=v.crewExe and v.vesselId = :vessel").setParameter("vessel", Integer.parseInt(vesseId));
            if (query2.list().size() > 0) {
                User crew = (User) query2.uniqueResult();
                crewEmail = crew.getEmail();
            }

            Query query3 = ss.createQuery("select u from User u, Vessel v where u=v.procExe and v.vesselId = :vessel").setParameter("vessel", Integer.parseInt(vesseId));
            if (query3.list().size() > 0) {
                User proc = (User) query3.uniqueResult();
                procEmail = proc.getEmail();
            }

            LOG.debug("Vessel ID :" + vesseId);
            LOG.debug("crewEmail :" + crewEmail);
            LOG.debug("procEmail :" + procEmail);
        } catch (HibernateException ex) {
            LOG.error(null, ex);
        } finally {
            if (ss != null) {
                ss.close();
            }
        }
    }
}
